package com.rrqs.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.czp.library.ArcProgress;
import com.litesuits.http.request.content.multi.MultipartBody;
import com.litesuits.http.request.content.multi.StringPart;
import com.rrqs.activity.common.Const;
import com.rrqs.activity.data.GetorderCheckResp;
import com.rrqs.net.AsyncHttpClient;
import com.rrqs.net.HttpResponseListener;
import com.rrqs.util.MyApplication;
import com.rrqs.utils.DateUtils;
import com.rrqs.utils.JsonUtils;
import com.zadtek.xmqishi.R;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.rrqs.activity.common.Const.TOURL;

/**
 * 我的统计
 * @author kuyukeji
 *
 */
public class MyCheckFragment extends FragmentActivity{

	private ImageView backid,iv_rili;
	private TextView topview, rightname; // 标题,右边的标题

	ArcProgress jinrizaixianPro;


	private PoiAdapter poiAdapter;
	private RecyclerView recyclerView;
	List<GetorderCheckResp.Daytimearr> data = new ArrayList<>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_mykq);
		
		backid = (ImageView) findViewById(R.id.backid);
		backid.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		topview = (TextView) findViewById(R.id.topview);
		topview.setText("我的考勤");
		rightname = (TextView) findViewById(R.id.rightname);
		rightname.setVisibility(View.GONE);
		iv_rili = (ImageView) findViewById(R.id.iv_rili);
		iv_rili.setVisibility(View.VISIBLE);
		iv_rili.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showRiqixuanzhe();
			}
		});
		jinrizaixianPro  = findViewById(R.id.myProgress01);

		recyclerView = findViewById(R.id.recyclerView);
		LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
		linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		recyclerView.setLayoutManager(linearLayoutManager);
		poiAdapter = new PoiAdapter(R.layout.wodetongji_item, data);
		recyclerView.setAdapter(poiAdapter);
		requestData(DateUtils.getMouth());
	}

	private void showRiqixuanzhe() {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = (c.get(Calendar.MONTH)+1);

				DatePickerDialog mydialog = new DatePickerDialog(MyCheckFragment.this, AlertDialog.THEME_HOLO_LIGHT,
						new DatePickerDialog.OnDateSetListener() {
							@Override
							public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
								String value = String.format("%d%d", year, monthOfYear+1);
								if (value.length() ==5){
									value = String.format("%d0%d", year, monthOfYear+1);
								}
								requestData(value);
							}
						}, year, month-1, 1);
				mydialog.show();

			DatePicker dp = findDatePicker((ViewGroup) mydialog.getWindow().getDecorView());
			if (dp != null) {
				((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
			}
	}

	private DatePicker findDatePicker(ViewGroup group) {
		if (group != null) {
			for (int i = 0, j = group.getChildCount(); i < j; i++) {
				View child = group.getChildAt(i);
				if (child instanceof DatePicker) {
					return (DatePicker) child;
				} else if (child instanceof ViewGroup) {
					DatePicker result = findDatePicker((ViewGroup) child);
					if (result != null)
						return result;
				}
			}
		}
		return null;
	}
	private void requestData(String mouth) {
		data.clear();
		poiAdapter.notifyDataSetChanged();

		AsyncHttpClient httpClient = new AsyncHttpClient(MyApplication.getInstace());

		SharedPreferences sp = com.rrqs.util.MyApplication.getInstace().getSharedPreferences(Const.PREF_NAME, Context.MODE_PRIVATE);
		String uid = sp.getString("uid", "");

		MultipartBody body = new MultipartBody();
		body.addPart(new StringPart("emp_id", uid));
		body.addPart(new StringPart("time", mouth));
		body.addPart(new StringPart("ince", "get_getorder_check"));
		httpClient.post(TOURL, body, new HttpResponseListener() {
			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
			}

			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(String status, String result) {
				super.onSuccess(status, result);
				try {
					Log.i("CYX我的考勤", new JSONObject(result).toString());
				}catch (Exception e){}
				GetorderCheckResp resp = JsonUtils.json2Class(result,GetorderCheckResp.class);
				if (resp.getStatus() == 1){

					final String progressStr = resp.getDaytime() + "";
					jinrizaixianPro  = findViewById(R.id.myProgress01);
					jinrizaixianPro.setOnCenterDraw(new ArcProgress.OnCenterDraw() {
						@Override
						public void draw(Canvas canvas, RectF rectF, float x, float y, float storkeWidth, int progress) {
							Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
							textPaint.setStrokeWidth(35);
							textPaint.setColor(getResources().getColor(R.color.green));
							textPaint.setTextSize(40);

							float textX = x-(textPaint.measureText(progressStr)/2);
							float textY = y-((textPaint.descent()+textPaint.ascent())/2);
							canvas.drawText(progressStr,textX,textY,textPaint);
						}
					});
					try{
						jinrizaixianPro.setProgress(0);
						double d = Double.parseDouble(resp.getDaytimeall().replace("%",""));
						int pro = (int)d*100/100;
						jinrizaixianPro.setProgress(pro);
					}catch (Exception e){
						e.printStackTrace();
					}

					setText(R.id.hourmonth,resp.getHourmonth() + "");
					setText(R.id.daymonth,resp.getDaymonth() + "");
					setText(R.id.rundmonth,resp.getRundmonth() + "");
					setText(R.id.notime,resp.getNotime() + "");

					if (resp.getDaytimearr() != null){
						data.addAll(resp.getDaytimearr());
						poiAdapter.notifyDataSetChanged();
					}
				}
			}
		});
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			assert data != null;
			if (requestCode == 1000) {
				Date date = new Date(data.getLongExtra("date", 0));
				DateUtils.convertDateToStr(date, "yyyyMMdd");
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}


	private class PoiAdapter extends BaseQuickAdapter<GetorderCheckResp.Daytimearr,BaseViewHolder> {
		public PoiAdapter(int layoutResId, @Nullable List<GetorderCheckResp.Daytimearr> data) {
			super(layoutResId, data);
		}

		@Override
		protected void convert(BaseViewHolder helper, GetorderCheckResp.Daytimearr item) {
			String address = "~~~~~~~";
			helper.setText(R.id.tv_datatime, item.getDatatime() + "");
			((ProgressBar)helper.getView(R.id.progress)).setProgress((int)item.getDatatimeall());
			helper.setText(R.id.tv_hour, item.getHour() + "");
			if ("未出勤".equals(item.getHour())){
				helper.setTextColor(R.id.tv_hour, getResources().getColor(R.color.red));
				(helper.getView(R.id.progress)).setVisibility(View.INVISIBLE);
			}
		}
	}

	private void setText(int id, String str){
		try{
			((TextView) findViewById(id)).setText(str);
		}catch (Exception e){
			e.printStackTrace();
		}

	}

}
